package org.loong.crypto.model.asn1.sm2;

import java.util.Enumeration;

import org.bouncycastle.asn1.ASN1EncodableVector;
import org.bouncycastle.asn1.ASN1Integer;
import org.bouncycastle.asn1.ASN1Object;
import org.bouncycastle.asn1.ASN1Primitive;
import org.bouncycastle.asn1.ASN1Sequence;
import org.bouncycastle.asn1.DERSequence;

public class SM2Signature extends ASN1Object {

    private ASN1Integer r;

    private ASN1Integer s;

    public SM2Signature(byte[] r, byte[] s) {
        this.r = new ASN1Integer(r);
        this.s = new ASN1Integer(s);
    }

    public SM2Signature(ASN1Sequence seq) {
        if (seq.size() != 2) {
            throw new IllegalArgumentException("Bad sequence size: " + seq.size());
        }
        
        Enumeration<?> e = seq.getObjects();
        this.r = ASN1Integer.getInstance(e.nextElement());
        this.s = ASN1Integer.getInstance(e.nextElement());
    }

    public static SM2Signature getInstance(Object obj) {
        if (obj instanceof SM2Signature) {
            return (SM2Signature) obj;
        } 
        
        if (obj != null) {
            return new SM2Signature(ASN1Sequence.getInstance(obj));
        }
        
        return null;
    }

    public ASN1Integer getR() {
        return r;
    }

    public ASN1Integer getS() {
        return s;
    }

    @Override
    public ASN1Primitive toASN1Primitive() {
        ASN1EncodableVector vector = new ASN1EncodableVector();
        vector.add(r);
        vector.add(s);
        return new DERSequence(vector);
    }
}